package com.panda.web.controller.order;

import com.panda.common.core.domain.R;
import com.panda.web.configuration.WxPayConfig;
import com.panda.web.entity.order.WechatOrder;
import com.panda.web.entity.product.OpenidProduct;
import com.panda.web.entity.product.Product;
import com.panda.web.entity.wechatinfo.WechatUserinfo;
import com.panda.web.mapper.order.WechatOrderMapper;
import com.panda.web.mapper.product.OpenidProductMapper;
import com.panda.web.mapper.product.ProductMapper;
import com.panda.web.mapper.wechatinfo.WechatUserinfoMapper;
import com.panda.web.service.order.impl.WxPayService;
import com.panda.web.utils.payutils.MiniWxPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.Random;

@Slf4j
@RestController
@RequestMapping("/api/payment")
public class PaymentController {

    private static final Logger logger = LoggerFactory.getLogger(PaymentController.class);

    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private WxPayConfig wxPayConfig;

    @Autowired
    private WechatOrderMapper orderMapper;
    @Autowired
    private OpenidProductMapper openidProductMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private WechatUserinfoMapper userinfoMapper;

    // 创建支付订单接口
    @PostMapping("/create")
    public R createOrder(@RequestBody WechatOrder order) {
        try {
            Map<String, String> orderResult = wxPayService.createOrder(order);

            if ("SUCCESS".equals(orderResult.get("result_code"))) {
                Map<String, String> jsApiParams = wxPayService.getJsApiParams(orderResult.get("prepay_id"));
                return R.ok(jsApiParams, 200, "ok");
            } else {
                throw new RuntimeException(orderResult.get("err_code_des"));
            }
        } catch (Exception e) {
            throw new RuntimeException("\"支付创建失败：\" " + e.getMessage());

        }
    }

    // 支付回调通知接口
    @PostMapping(value = "/notify", produces = "application/xml;charset=UTF-8")
    public String paymentNotify(@RequestBody String xmlData) {
        try {
            Map<String, String> notifyMap = MiniWxPayUtil.xmlToMap(xmlData);

            // 验证签名
            String sign = notifyMap.get("sign");
            notifyMap.remove("sign");
            String calcSign = MiniWxPayUtil.generateSignature(notifyMap, wxPayConfig.getApiKey());

            if (!sign.equals(calcSign)) {
                return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>";
            }
            // 处理支付成功业务逻辑
            if ("SUCCESS".equals(notifyMap.get("return_code"))) {
                String orderId = notifyMap.get("out_trade_no");
                String transactionId = notifyMap.get("transaction_id");
                int totalFee = Integer.parseInt(notifyMap.get("total_fee"));


                log.info("支付成功：订单号={}, 微信交易号={}, 金额={}分", orderId, transactionId, totalFee);
                // 5. 查询订单
                WechatOrder order = orderMapper.findByOrderId(orderId);
                if (order != null) {
                    order.setPayStatus("已支付");
                    order.setTransactionId(transactionId);
                    order.setPayTime(new Date());
                    orderMapper.updateById(order);
                    //添加用户已购买产品的产品表
                    Product product = productMapper.selectById(order.getProductId());//产品表
                    OpenidProduct openidProduct = openidProductMapper.findByProductIdAndOpenId(order.getOpenid(), order.getProductId());
                    Date date = new Date();
                    SimpleDateFormat stringDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String formattedDate = stringDate.format(date);

                    if (product.getProductId() == 10) {
                        //判断是否为空，为空 说明第一次购买这个产品，否则不是第一次
                        if (openidProduct != null) {//更新原商品状态为可使用

                            openidProduct.setCount(openidProduct.getCount() + order.getOrderCount());
                            openidProductMapper.updateById(openidProduct);


                        } else {
                            OpenidProduct openidProductNew = new OpenidProduct();
                            openidProductNew.setOpenid(order.getOpenid());
                            openidProductNew.setProductId(order.getProductId());
                            openidProductNew.setProductType(product.getProductType());
                            openidProductNew.setProductName(product.getProductName());
                            openidProductNew.setProductPrice(product.getProductPrice());
                            openidProductNew.setAiCount(product.getAiCount());
                            openidProductNew.setDay(product.getProductType());
                            openidProductNew.setCreateTime(date);
                            openidProductNew.setCreationTime(formattedDate);
                            openidProductNew.setCount(order.getOrderCount());
                            openidProductMapper.insert(openidProductNew);
                        }
                        //更具openid 更改剩余次数
                        WechatUserinfo userinfo = userinfoMapper.findByOpenid(order.getOpenid());
                        userinfo.setAiInterview(userinfo.getAiInterview()+order.getOrderCount());
                        userinfoMapper.updateById(userinfo);

                    } else {
                        //判断是否为空，为空 说明第一次购买这个产品，否则不是第一次
                        if (openidProduct != null) {//更新原商品状态为可使用
                            if (Objects.equals(openidProduct.getStatus(), "0")) {//说明没到期

                                //在该套餐的上加时间
                                if (openidProduct.getProductId() == 2 || openidProduct.getProductId() == 3 || openidProduct.getProductId() == 4 || openidProduct.getProductId() == 8 || openidProduct.getProductId() == 9) {
                                    openidProduct.setDay(String.valueOf(Integer.valueOf(openidProduct.getDay()) + Integer.valueOf(openidProduct.getProductType())));
                                }
                                if (product.getProductId() == 2 || product.getProductId() == 3) {
                                    openidProduct.setAiCount(openidProduct.getAiCount() + product.getAiCount());
                                }
                                openidProduct.setCount(openidProduct.getCount() + 1);
                                openidProductMapper.updateById(openidProduct);
                            } else {//到期了
                                openidProduct.setStatus("0");
                                openidProduct.setCreationTime(formattedDate);//新购买时间，更新购买次数
                                if (product.getProductId() == 2 || product.getProductId() == 3) {
                                    openidProduct.setAiCount(openidProduct.getAiCount() + product.getAiCount());
                                }
                                openidProduct.setCreateTime(date);
                                openidProduct.setCount(openidProduct.getCount() + 1);
                                openidProductMapper.updateById(openidProduct);
                            }

                        } else {
                            OpenidProduct openidProductNew = new OpenidProduct();
                            openidProductNew.setOpenid(order.getOpenid());
                            openidProductNew.setProductId(order.getProductId());
                            openidProductNew.setProductType(product.getProductType());
                            openidProductNew.setProductName(product.getProductName());
                            openidProductNew.setProductPrice(product.getProductPrice());
                            openidProductNew.setAiCount(product.getAiCount());
                            openidProductNew.setDay(product.getProductType());
                            openidProductNew.setCreateTime(date);
                            openidProductNew.setCreationTime(formattedDate);
                            openidProductNew.setCount(1);
                            openidProductMapper.insert(openidProductNew);
                        }
                    }

                }

//原支付逻辑2025-07-04前
//            // 处理支付成功业务逻辑
//            if ("SUCCESS".equals(notifyMap.get("return_code"))) {
//                String orderId = notifyMap.get("out_trade_no");
//                String transactionId = notifyMap.get("transaction_id");
//                int totalFee = Integer.parseInt(notifyMap.get("total_fee"));
//
//
//                log.info("支付成功：订单号={}, 微信交易号={}, 金额={}分", orderId, transactionId, totalFee);
//                // 5. 查询订单
//                WechatOrder order = orderMapper.findByOrderId(orderId);
//                if (order != null) {
//                    order.setPayStatus("已支付");
//                    order.setTransactionId(transactionId);
//                    order.setPayTime(new Date());
//                    orderMapper.updateById(order);
//                    //添加用户已购买产品的产品表
//                    Product product = productMapper.selectById(order.getProductId());//产品表
//                    OpenidProduct openidProduct = openidProductMapper.findByProductIdAndOpenId(order.getOpenid(), order.getProductId());
//                    Date date = new Date();
//                    SimpleDateFormat stringDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                    String formattedDate = stringDate.format(date);
//
//                    //判断是否为空，为空 说明第一次购买这个产品，否则不是第一次
//                    if (openidProduct != null) {//更新原商品状态为可使用
//                        if (Objects.equals(openidProduct.getStatus(), "0")) {//说明没到期
//                            //在该套餐的上加时间
//                            if (openidProduct.getProductId() == 2 || openidProduct.getProductId() == 3 || openidProduct.getProductId() == 4 || openidProduct.getProductId() == 8 || openidProduct.getProductId() == 9) {
//                                openidProduct.setDay(String.valueOf(Integer.valueOf(openidProduct.getDay()) + Integer.valueOf(openidProduct.getProductType())));
//                            }
//                            if (product.getProductId() == 2 || product.getProductId() == 3 ) {
//                                openidProduct.setAiCount(openidProduct.getAiCount() + product.getAiCount());
//                            }
//                            openidProduct.setCount(openidProduct.getCount() + 1);
//                            openidProductMapper.updateById(openidProduct);
//                        } else {//到期了
//                            openidProduct.setStatus("0");
//                            openidProduct.setCreationTime(formattedDate);//新购买时间，更新购买次数
//                            if (product.getProductId() == 2 || product.getProductId() == 3) {
//                                openidProduct.setAiCount(openidProduct.getAiCount() + product.getAiCount());
//                            }
//                            openidProduct.setCreateTime(date);
//                            openidProduct.setCount(openidProduct.getCount() + 1);
//                            openidProductMapper.updateById(openidProduct);
//                        }
//
//
////                    openidProduct.setStatus("0");
////                    openidProduct.setCreationTime(formattedDate);//新购买时间，更新购买次数
////                    if (product.getProductId()==2||product.getProductId()==3){
////                        openidProduct.setAiCount(openidProduct.getAiCount()+product.getAiCount());
////                    }
////                    openidProduct.setCreateTime(date);
////                    openidProduct.setCount(openidProduct.getCount() + 1);
////                    openidProductMapper.updateById(openidProduct);
//                    } else {
//                        OpenidProduct openidProductNew = new OpenidProduct();
//                        openidProductNew.setOpenid(order.getOpenid());
//                        openidProductNew.setProductId(order.getProductId());
//                        openidProductNew.setProductType(product.getProductType());
//                        openidProductNew.setProductName(product.getProductName());
//                        openidProductNew.setProductPrice(product.getProductPrice());
//                        openidProductNew.setAiCount(product.getAiCount());
//                        openidProductNew.setDay(product.getProductType());
//                        openidProductNew.setCreateTime(date);
//                        openidProductNew.setCreationTime(formattedDate);
//                        openidProductNew.setCount(1);
//                        openidProductMapper.insert(openidProductNew);
//                    }
//                }

                // 返回成功响应
                return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            }

            return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[业务失败]]></return_msg></xml>";
        } catch (Exception e) {
            return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[系统异常]]></return_msg></xml>";
        }
    }
}